package com.lg.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.cms.dto.ImageDTO;
import com.lg.cms.entity.*;
import com.lg.cms.mapper.*;
import com.lg.cms.service.ArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lg.cms.utils.RedisUtil;
import com.lg.cms.utils.StatsUtil;
import com.lg.cms.vo.LayerTableVO;
import com.lg.cms.vo.admin.SuperArticleVO;
import com.lg.cms.vo.admin.addArticleVO;
import com.lg.cms.vo.news.ArticleVO;
import com.lg.cms.vo.news.ImageVO;
import com.lg.cms.vo.news.VideoVO;
import com.qiniu.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 文章表 服务实现类
 * </p>
 *
 * @author lg
 * @since 2020-09-21
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    ArticleTagsMapper articleTagsMapper;
    @Autowired
    ArticleTypeMapper articleTypeMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    TagsMapper tagsMapper;
    @Resource
    RedisUtil redisUtil;
    @Resource
    StatsUtil statsUtil;
    @Autowired
    CommentMapper commentMapper;

    @Override
    public String updateArticle(Article article, Set<Integer> tagsIdSet) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<Article>();
        queryWrapper.eq("id", article.getId());
        //DocSet s = docSetService.getOne(queryWrapper);
        //docSetService.updateById(s);
        articleMapper.update(article,queryWrapper);
        System.out.println(article.getTop());
        System.out.println("第一次更新》》》》》》》》》》》》》》》》》》》》》》");
        return "更新成功";

    }

    @Override
    public Map<String, Set<String>> getTypeMap() {
        Map<String, Set<String>> map = new HashMap<>();
        String[] imageArr = "jpg.jpeg.gif.png.bmp".split("\\.");
        String[] videoArr = "mp4.avi".split("\\.");
        Set<String> imageSet = new HashSet<>(Arrays.asList(imageArr));
        Set<String> videoSet = new HashSet<>(Arrays.asList(videoArr));

        map.put("image", imageSet);
        map.put("video", videoSet);
        return map;
    }

    /**
     * 新增文章, 暂不做外键id验证
     *
     * @param article
     * @param tagsIdSet
     * @return
     */
    @Override
    @Transactional
    public R<?> addArticle(Article article, Set<Integer> tagsIdSet) {
        try {
            int result = articleMapper.insert(article);
            if (result == 0) {
                return R.failed("创建文章失败");
            }
            boolean r = addArticleTags(article.getId(), tagsIdSet);
            if (!r) {
                throw new Exception("写入标签是出错");
            }
            
            return R.ok(article);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.failed(e.getMessage());
        }

    }

    /**
     * article转VO对象
     *
     * @param article
     * @return
     */
    @Override
    public SuperArticleVO toSuperArticleVO(Article article) {
        SuperArticleVO vo = new SuperArticleVO();
        vo.setArticleTypeId(article.getArticleTypeId());
        vo.setAuthor(article.getAuthor());
        vo.setId(article.getId());
        vo.setSuperUserId(article.getSuperUserId());
        vo.setCoverImage(article.getCoverImage());
        vo.setCategoryId(article.getCategoryId());
        vo.setVideoUrl(article.getVideoUrl());
        vo.setComment(article.getComment());
        vo.setCreateTime(article.getCreateTime());
        vo.setImageJson(article.getImageJson());
        vo.setRecommended(article.getRecommended());
        vo.setDescription(article.getDescription());
        vo.setContent(article.getContent());
        vo.setTitle(article.getTitle());
        vo.setCoverImage(article.getCoverImage());
        vo.setTop(article.getTop());
        vo.setState(article.getState());
        vo.setCategoryName(categoryMapper.selectById(vo.getCategoryId()).getName());
        vo.setArticleTypeName(articleTypeMapper.selectById(vo.getArticleTypeId()).getName());
        return vo;
    }

    /**
     * 获取文章标签列表
     *
     * @param articleId
     * @return
     */
    @Override
    public List<Tags> getTagsListByArticleId(Integer articleId) {
        List<Tags> list = new ArrayList<>();
        Set<Integer> tagsIdSet = new HashSet<>();
        articleTagsMapper.selectList(
                new QueryWrapper<ArticleTags>().eq("article_id", articleId))
                .forEach(v -> tagsIdSet.add(v.getTagsId()));
        for (Integer id : tagsIdSet) {
            list.add(tagsMapper.selectById(id));
        }
        return list;
    }

    /**
     * 获取某栏目文章列表(第一页), 前台展示
     *
     * @return
     */
    @Override
    public List<ArticleVO> getListByCategoryId(Integer categoryId) {
        categoryId = this.isArticle(categoryId)? categoryId: null;
        List<ArticleVO> list = new ArrayList<>();
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId);
        wrapper.orderByDesc("update_time");
        Page<Article> page = new Page<>(1, (Integer) redisUtil.get("cms:pageSize"));
        articleMapper.selectPage(page, wrapper);
        page.getRecords().forEach(v -> list.add(this.toArticleVO((Article) v)));
        return list;
    }
    /**
     * 获取视频分类列表(第一页), 前台展示
     * @return
     */
    @Override
    public List<VideoVO> getListByVideo(QueryWrapper wrapper) {
        List<VideoVO> list = new ArrayList<>();
        Page<Article> page = new Page(1, (Integer)redisUtil.get("cms:pageSize"));
//        QueryWrapper<Article> wrapper = this.videoWrapper();
        wrapper = this.videoWrapper(wrapper);
        articleMapper.selectPage(page, wrapper);
        page.getRecords().forEach(v -> list.add(this.toVideoVO((Article) v)));
        return list;
    }


    /**
     * 获取图片分类列表(第一页), 前台展示
     * @return
     */
    @Override
    public List<ImageVO> getListByImage(QueryWrapper wrapper) {
        List<ImageVO> list = new ArrayList<>();
        Page<Article> page = new Page(1, (Integer)redisUtil.get("cms:pageSize"));
        wrapper = this.imageWrapper(wrapper);
        articleMapper.selectPage(page, wrapper);
        page.getRecords().forEach(v -> list.add(this.toImageVO((Article) v)));
        return list;
    }
    /**
     * 获取推荐文章列表(第一页), 前台展示
     * @return
     */
    @Override
    public List<ArticleVO> getListByRecommended() {
        List<ArticleVO> list = new ArrayList<>();
        QueryWrapper<Article> wrapper = this.recommendedWrapper();
        Page<Article> page = new Page<>(1, (Integer) redisUtil.get("cms:pageSize"));
        articleMapper.selectPage(page, wrapper);
        page.getRecords().forEach(v -> list.add(this.toArticleVO((Article) v)));
        return list;
    }

    /**
     * 获取某标签文章列表(第一页), 前台展示
     * @param tagsId
     * @return
     */
    @Override
    public List<ArticleVO> getListByTagsId(Integer tagsId) {
        List<ArticleVO> list = new ArrayList<>();
        Page<ArticleTags> page = new Page<>(1,(Integer)redisUtil.get("cms:pageSize"));
        Set<Integer> articleIdSet = new HashSet<>();
        QueryWrapper<ArticleTags> wrapper = new QueryWrapper<>();
        wrapper.eq("tags_id", tagsId);
        wrapper.orderByDesc("create_time");
        articleTagsMapper.selectPage(page, wrapper);
        page.getRecords().forEach(v -> articleIdSet.add(v.getArticleId()));
        for(Integer articleId: articleIdSet){
            Article temp = articleMapper.selectById(articleId);
            if(temp != null){
                list.add(this.toArticleVO(temp));
            }
        }

        return list;
    }

    /**
     * 获取搜索第一页
     * @param wrapper
     * @return
     */
    @Override
    public List<ArticleVO> getListByWrapper(QueryWrapper wrapper, String value) {
        List<ArticleVO> list = new ArrayList<>();
        wrapper.orderByDesc("update_time");
        Integer categoryImageId = categoryMapper.selectOne(new QueryWrapper<Category>().eq("name", "图片")).getId();
        Integer categoryVideoId = categoryMapper.selectOne(new QueryWrapper<Category>().eq("name", "视频")).getId();
        wrapper.ne("category_id", categoryImageId);
        wrapper.ne("category_id", categoryVideoId);
        Page<Article> page = new Page<>(1,(Integer)redisUtil.get("cms:pageSize"));
        articleMapper.selectPage(page, wrapper);
        page.getRecords().forEach(v -> list.add(this.toSelectArticleVO(v, value)));
        return list;
    }

    /**
     * 获取搜索page对象
     * @param wrapper
     * @param pageNum
     * @return
     */

    @Override
    public Page<ArticleVO> getPageByWrapper(QueryWrapper wrapper, Integer pageNum, String value) {
        List<ArticleVO> list = new ArrayList<>();
        wrapper.orderByDesc("update_time");
        Integer categoryImageId = categoryMapper.selectOne(new QueryWrapper<Category>().eq("name", "图片")).getId();
        Integer categoryVideoId = categoryMapper.selectOne(new QueryWrapper<Category>().eq("name", "视频")).getId();
        wrapper.ne("category_id", categoryImageId);
        wrapper.ne("category_id", categoryVideoId);
        Page page = new Page<>(pageNum,(Integer)redisUtil.get("cms:pageSize"));
        articleMapper.selectPage(page, wrapper);
        page.getRecords().forEach(v -> list.add(this.toSelectArticleVO((Article) v, value)));
        page.setRecords(list);
        return page;
    }





//转换成boolean 转换成int

    public int IntBoolean(boolean state){
        int ui=0;
        if (state){

            ui=1;

        }

      return ui;

    }





//显示布尔类型判断

    public   List<addArticleVO> booelanfieid(List<addArticleVO>  ls){
        for (addArticleVO aavo:ls
        ) {
            if (aavo.getState()){
                aavo.setStates("是");
            }else{
                aavo.setStates("否");
            }
            if (aavo.getTop()){
                aavo.setTops("是");
            }else{
                aavo.setTops("否");
            }
            if (aavo.getComment()){
                aavo.setComments("是");
            }else{
                aavo.setComments("否");
            }
            if (aavo.getRecommended()){
                aavo.setRecommendeds("是");
            }else{
                aavo.setRecommendeds("否");
            }



        }
        return ls;
    }





    @Override
    public LayerTableVO findByPage(Integer currPage, Integer pageSize) {


        //where 小于 是lt 不等于是ne 大于等于 ge likelift左模糊 likerghit 右模糊  多where联合查询是inSql
        //where orderByDesc 降序  orederByAsc 升序   having 排序后条件

        //selectOne只能一一条数据
//  Article pages= articleMapper.selectOne((Wrapper<Article>) queryWrapper.ne("name","0"));
        //分页查询(第几页，每页几条数据)

//        IPage<Article> page1
        System.out.println("currPage"+currPage);
        System.out.println("pageSize"+pageSize);
        QueryWrapper queryWrapper=new QueryWrapper();
        IPage<addArticleVO> pg= articleMapper.selectAll(new Page<addArticleVO>(currPage,pageSize),null);

        LayerTableVO lt= new LayerTableVO();
        List<addArticleVO> ls= pg.getRecords();
        lt.setData(booelanfieid(ls));
        long count=pg.getTotal();
        lt.setCount(count);
        lt.setCode(0);

        //每页几条数据 size)
        //数据总条数 Total
        // getRecords获取数据

        //分页查询map

//        articleMapper.selectMapsPage(,null).getRecords().forEach(System.out::println);



        //查询主键
//        articleMapper.selectObjs(null);



        //where 多条件 Map只能是等值判断，如果需要逻辑判断则 需要mapper来处理
//        Map map=new HashMap();
//        map.put("name","马书昌");
//        map.put("top",2);



//        Article sds= articleMapper.selectOne((Wrapper<Article>) queryWrapper.allEq(map));





              /*模糊查询
    			.like()*/
           //不加任何条件全部查询
//          Article sd= (Article) articleMapper.selectList(null);
//           articleMapper.selectList(null).forEach(System.out::println);
             //通过主键查询
//           Article s=  articleMapper.selectById(1);
//           articleMapper.selectBatchIds(Arrays.asList(7,8,9)).forEach(System.out::println);






//        System.out.println("count"+page.getTotal());
//        System.out.println("R_SIZE:" + page.getRecords().size());
//        List<Article> articleVOList = new ArrayList<>();


        return lt;
    }

    /**
     * id删除
     * @param id
     * @return
     */

    @Override
    public int deleteArticle(Integer id) {


        return articleMapper.deleteById(id);
    }

    /**
     * id 批量删除
     * @param allid
     * @return
     */

    @Override
    public int AlldeleteArticle(int[] allid) {
        ArrayList al=new ArrayList();
      for (int i=0;i<allid.length; i++)
          al.add(allid[i]);
        return articleMapper.deleteBatchIds(al);
    }

    /**
     * 分页条件查询（作者，类型，发布类型 ）
     * @param author
     * @param article_type_ids
     * @param state
     * @param tagsId
     * @param pageNum
     * @return
     */

    @Override
    public LayerTableVO fuzzyAllList(String author, Integer article_type_ids, boolean state, Integer tagsId, Integer pageNum) {
        int states=IntBoolean(state);

        QueryWrapper wrapper=new QueryWrapper();
        Map map=new HashMap();
        map.put("state",states);
        map.put("author",author);
        map.put("article_type_id",article_type_ids);
        wrapper.allEq(map);
        IPage<addArticleVO> pg= articleMapper.selectAlls(new Page<addArticleVO>(tagsId,pageNum),wrapper);
        LayerTableVO lt= new LayerTableVO();
        List<addArticleVO> ls= pg.getRecords();
        lt.setData(booelanfieid(ls));
        System.out.println(lt.getData());
        System.out.println("Total"+pg.getTotal());
        long count=pg.getTotal();
        lt.setCount(count);
        lt.setCode(0);
        return lt;
    }

    /**
     * 单个查看
     */



    /**
     * 通过作者查询
     * @param author
     * @param tagsId
     * @param pageNum
     * @return
     */

    @Override
    public LayerTableVO fuzzyAllList(String author, Integer tagsId, Integer pageNum) {
        QueryWrapper wrapper=new QueryWrapper();
        Map map=new HashMap();
        map.put("author",author);
        wrapper.allEq(map);
        IPage<addArticleVO> pg= articleMapper.selectAlls(new Page<addArticleVO>(tagsId,pageNum),wrapper);
        LayerTableVO lt= new LayerTableVO();
        List<addArticleVO> ls= pg.getRecords();
        lt.setData(booelanfieid(ls));
        System.out.println(lt.getData());
        System.out.println("Total"+pg.getTotal());
        long count=pg.getTotal();
        lt.setCount(count);
        lt.setCode(0);
        return lt;
    }

    /**
     * 通过类型查询
     * @param article_type_ids
     * @param tagsId
     * @param pageNum
     * @return
     */

    @Override
    public LayerTableVO fuzzyAllList(Integer article_type_ids, Integer tagsId, Integer pageNum) {
        QueryWrapper wrapper=new QueryWrapper();
        Map map=new HashMap();
        map.put("article_type_id",article_type_ids);
        wrapper.allEq(map);
        IPage<addArticleVO> pg= articleMapper.selectAlls(new Page<addArticleVO>(tagsId,pageNum),wrapper);
        LayerTableVO lt= new LayerTableVO();
        List<addArticleVO> ls= pg.getRecords();
        lt.setData(booelanfieid(ls));
        System.out.println(lt.getData());
        System.out.println("Total"+pg.getTotal());
        long count=pg.getTotal();
        lt.setCount(count);
        lt.setCode(0);
        return lt;
    }

    /***
     * 通过发布状态
     * @param state
     * @param tagsId
     * @param pageNum
     * @return
     */

    @Override
    public LayerTableVO fuzzyAllList(boolean state, Integer tagsId, Integer pageNum) {
        QueryWrapper wrapper=new QueryWrapper();
        int states=IntBoolean(state);
        Map map=new HashMap();
        map.put("state",states);
        wrapper.allEq(map);
        IPage<addArticleVO> pg= articleMapper.selectAlls(new Page<addArticleVO>(tagsId,pageNum),wrapper);
        LayerTableVO lt= new LayerTableVO();
        List<addArticleVO> ls= pg.getRecords();
        lt.setData(booelanfieid(ls));
        System.out.println(lt.getData());
        System.out.println("Total"+pg.getTotal());
        long count=pg.getTotal();
        lt.setCount(count);
        lt.setCode(0);
        return lt;


    }

    /**
     * 通过状态，类型查询
     * @param article_type_ids
     * @param states
     * @param tagsId
     * @param pageNum
     * @return
     */

    @Override
    public LayerTableVO fuzzyAllList(Integer article_type_ids, boolean states, Integer tagsId, Integer pageNum) {
        int state=IntBoolean(states);
        QueryWrapper wrapper=new QueryWrapper();
        Map map=new HashMap();
        map.put("state",state);
        map.put("article_type_id",article_type_ids);
        wrapper.allEq(map);
        IPage<addArticleVO> pg= articleMapper.selectAlls(new Page<addArticleVO>(tagsId,pageNum),wrapper);
        LayerTableVO lt= new LayerTableVO();
        List<addArticleVO> ls= pg.getRecords();
        lt.setData(booelanfieid(ls));
        System.out.println(lt.getData());
        System.out.println("Total"+pg.getTotal());
        long count=pg.getTotal();
        lt.setCount(count);
        lt.setCode(0);
        return lt;
    }

    /**
     * 通过作者，状态查询
     * @param author
     * @param states
     * @param tagsId
     * @param pageNum
     * @return
     */
    @Override
    public LayerTableVO fuzzyAllList(String author, boolean states, Integer tagsId, Integer pageNum) {
        int state=IntBoolean(states);
        QueryWrapper wrapper=new QueryWrapper();
        Map map=new HashMap();
        map.put("state",state);
        map.put("author",author);
        wrapper.allEq(map);
        IPage<addArticleVO> pg= articleMapper.selectAlls(new Page<addArticleVO>(tagsId,pageNum),wrapper);
        LayerTableVO lt= new LayerTableVO();
        List<addArticleVO> ls= pg.getRecords();
        lt.setData(booelanfieid(ls));
        System.out.println(lt.getData());
        System.out.println("Total"+pg.getTotal());
        long count=pg.getTotal();
        lt.setCount(count);
        lt.setCode(0);
        return lt;
    }

    /**
     * 通过作者，类型查询
     * @param author
     * @param article_type_ids
     * @param tagsId
     * @param pageNum
     * @return
     */
    @Override
    public LayerTableVO fuzzyAllList(String author, Integer article_type_ids, Integer tagsId, Integer pageNum) {
        QueryWrapper wrapper=new QueryWrapper();
        Map map=new HashMap();
        map.put("author",author);
        map.put("article_type_id",article_type_ids);
        wrapper.allEq(map);
        IPage<addArticleVO> pg= articleMapper.selectAlls(new Page<addArticleVO>(tagsId,pageNum),wrapper);
        LayerTableVO lt= new LayerTableVO();
        List<addArticleVO> ls= pg.getRecords();
        lt.setData(booelanfieid(ls));
        System.out.println(lt.getData());
        System.out.println("Total"+pg.getTotal());
        long count=pg.getTotal();
        lt.setCount(count);
        lt.setCode(0);
        return lt;
    }

    @Override
    public List<addArticleVO> selectArticle(Integer id) {



        return articleMapper.select(null,id);
    }


    /**
     * 查询状态
     * @return
     */
    @Override
    public List<addArticleVO> Binding_typeArticle() {

       List<addArticleVO> ly= articleMapper.selectAllS(null);

        booelanfieid(ly);

        return ly;
    }


    /**
     * 获取某标签文章Page对象
     * @param tagsId
     * @param pageNum
     * @return
     */
    @ResponseBody
    @Override
    public Page getPageByTagsId(Integer tagsId, Integer pageNum) {

        Page page = new Page<>(pageNum,(Integer)redisUtil.get("cms:pageSize"));
        Set<Integer> articleIdSet = new HashSet<>();
        List<ArticleVO> articleVOList = new ArrayList<>();
        QueryWrapper<ArticleTags> wrapper = new QueryWrapper<>();
        wrapper.eq("tags_id", tagsId);
        wrapper.orderByDesc("create_time");
        articleTagsMapper.selectPage(page, wrapper);
        for(Object object: page.getRecords()){
            ArticleTags temp = (ArticleTags)object;
            articleIdSet.add(temp.getArticleId());
        }
        for(Integer id: articleIdSet){
            Article temp = articleMapper.selectById(id);
            if(temp != null){
                articleVOList.add(this.toArticleVO(temp));

            }
        }

//        LayerTableVO lt= new LayerTableVO();
//
//        page.setRecords(articleVOList);
//        List ls=page.getRecords();
//        System.out.println(page.getSize());
//        lt.setData(ls);
//        System.out.println(lt.getData());
        return page;
    }

    @Override
    public Page<ArticleVO> getPageByCategoryId(Integer categoryId, Integer pageNum) {
        categoryId = this.isArticle(categoryId)? categoryId: null;
        List<ArticleVO> list = new ArrayList<>();
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId);
        wrapper.orderByDesc("update_time");
        Page page = new Page<>(pageNum, (Integer) redisUtil.get("cms:pageSize"));
        articleMapper.selectPage(page, wrapper);
        page.getRecords().forEach(v -> list.add(this.toArticleVO((Article) v)));
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<ImageVO> getPageByImage(Integer pageNum, QueryWrapper wrapper) {
        List<ImageVO> list = new ArrayList<>();
        Page page = new Page(pageNum, (Integer)redisUtil.get("cms:pageSize"));
        wrapper = this.imageWrapper(wrapper);

        articleMapper.selectPage(page, wrapper);

        for(Object a: page.getRecords()){
            list.add(this.toImageVO((Article)a));
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<VideoVO> getPageByVideo(Integer pageNum, QueryWrapper wrapper) {
        List<VideoVO> list = new ArrayList<>();
        Page page = new Page(pageNum, (Integer)redisUtil.get("cms:pageSize"));
        wrapper = this.videoWrapper(wrapper);
        articleMapper.selectPage(page, wrapper);
        for(Object a: page.getRecords()){
            list.add(this.toVideoVO((Article)a));
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public Page<ArticleVO> getPageByRecommended(Integer pageNum) {
        List<ArticleVO> list = new ArrayList<>();
        QueryWrapper<Article> wrapper = this.recommendedWrapper();
        Page page = new Page<>(pageNum, (Integer) redisUtil.get("cms:pageSize"));
        articleMapper.selectPage(page, wrapper);
        for(Object article: page.getRecords()){
            list.add(this.toArticleVO((Article)article));
        }
        page.setRecords(list);
        return page;
    }

    /**
     * 转文章VO对象
     *
     * @param article
     * @return
     */
    @Override
    public ArticleVO
    toArticleVO(Article article) {
        ArticleVO vo = new ArticleVO();
        vo.setArticle(article);
        vo.setTitle(article.getTitle());
        vo.setAuthor(article.getAuthor());
        vo.setArticleId(article.getId());
        vo.setComment(article.getComment());
        vo.setCreateTime(article.getCreateTime());
        vo.setCoverImage(article.getCoverImage());
        vo.setDescription(article.getDescription());
        vo.setRecommended(article.getRecommended());
        vo.setUrl("/info_article/" + article.getId());
        vo.setMarkdownContent(article.getMarkdownContent());
        vo.setTop(article.getTop());
        vo.setCategoryName(categoryMapper.selectById(article.getCategoryId()).getName());
        vo.setLikes(statsUtil.getArticleLike(article.getId()));
        vo.setVisits(statsUtil.getArticleView(article.getId()));
        vo.setCommentNumber(commentMapper.selectCount(
                new QueryWrapper<Comment>().eq("article_id", article.getId())));
//        vo.setIsLike(statsUtil.isLike());
        return vo;
    }

    /**
     * 转文章图片VO对象
     *
     * @param article
     * @return
     */
    @Override
    public ImageVO toImageVO(Article article) {
        ImageVO vo = new ImageVO();
        List<ImageDTO> imageDTOList = new ArrayList<>();
        vo.setTitle(article.getTitle());
        vo.setArticleId(article.getId());
        vo.setAuthor(article.getAuthor());
        vo.setCreateTime(article.getCreateTime());
        vo.setCoverImage(article.getCoverImage());
        vo.setComment(article.getComment());
        vo.setRecommended(article.getRecommended());
        vo.setTop(article.getTop());
        vo.setArticle(article);
        vo.setUrl("/info_image/" + article.getId());
        List<Map<String, String>> jsonList = Json.decode(article.getImageJson(), List.class);
        for(Map<String, String> map: jsonList){
            ImageDTO temp = new ImageDTO();
            for(Map.Entry<String, String> entry: map.entrySet()){
                if(entry.getKey().equals("imageUrl")){
                    temp.setImageUrl(entry.getValue());
                }else{
                    temp.setTitle(entry.getValue());
                }
            }
            imageDTOList.add(temp);
        }
        vo.setImageDTOList(imageDTOList);

        vo.setLikes(statsUtil.getArticleLike(article.getId()));
        vo.setVisits(statsUtil.getArticleView(article.getId()));
        vo.setCommentNumber(commentMapper.selectCount(
                new QueryWrapper<Comment>().eq("article_id", article.getId())));
//        vo.setIsLike(statsUtil.isLike());
        return vo;
    }

    /**
     * 转文章视频VO对象
     *
     * @param article
     * @return
     */
    @Override
    public VideoVO toVideoVO(Article article) {
        VideoVO vo = new VideoVO();
        vo.setTitle(article.getTitle());
        vo.setArticleId(article.getId());
        vo.setAuthor(article.getAuthor());
        vo.setCoverImage(article.getCoverImage());
        vo.setVideoUrl(article.getVideoUrl());
        vo.setCreateTime(article.getCreateTime());
        vo.setTop(article.getTop());
        vo.setComment(article.getComment());
        vo.setRecommended(article.getRecommended());
        vo.setArticle(article);
        vo.setUrl("/info_video/" + article.getId());

        vo.setLikes(statsUtil.getArticleLike(article.getId()));
        vo.setVisits(statsUtil.getArticleView(article.getId()));
        vo.setCommentNumber(commentMapper.selectCount(
                new QueryWrapper<Comment>().eq("article_id", article.getId())));
//        vo.setIsLike(statsUtil.isLike());
        return vo;
    }

    /**
     * 创建 文章标签多对多表关系
     *
     * @param articleId
     * @param tagsIdSet
     * @return
     */
    private boolean addArticleTags(Integer articleId, Set<Integer> tagsIdSet) {
        int result = 0;
        for (Integer tagsId : tagsIdSet) {
            ArticleTags temp = new ArticleTags();
            temp.setArticleId(articleId);
            temp.setTagsId(tagsId);
            result += articleTagsMapper.insert(temp);
        }
        if (result == tagsIdSet.size()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 判断是否为文章栏目(非图片, 视频)
     * @param categoryId
     * @return
     */
    private boolean isArticle(Integer categoryId){
        Category category = categoryMapper.selectById(categoryId);
        String categoryName = "";
        if (category != null) {
            categoryName = category.getName();
            if(categoryName.equals("图片") || categoryName.equals("视频")){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }

    }

    /**
     * 视频类型文章查询构造器
     * @return
     */
    private QueryWrapper<Article> videoWrapper(QueryWrapper wrapper){
        Category category = categoryMapper.selectOne(new QueryWrapper<Category>().eq("name", "视频"));
        if(wrapper == null){
            wrapper = new QueryWrapper();
        }
        wrapper.orderByDesc("update_time");
        wrapper.eq("category_id", category.getId());
        return wrapper;
    }

    /**
     * 图片类型文章查询构造器
     * @return
     */
    private QueryWrapper<Article> imageWrapper(QueryWrapper wrapper){
        Category category = categoryMapper.selectOne(new QueryWrapper<Category>().eq("name", "图片"));
        if(wrapper == null){
            wrapper = new QueryWrapper();
        }
        wrapper.orderByDesc("update_time");
        wrapper.eq("category_id", category.getId());
        return wrapper;
    }
    private QueryWrapper<Article> recommendedWrapper(){
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        Integer categoryImageId = categoryMapper.selectOne(new QueryWrapper<Category>().eq("name", "图片")).getId();
        Integer categoryVideoId = categoryMapper.selectOne(new QueryWrapper<Category>().eq("name", "视频")).getId();
        if(wrapper == null){
            wrapper = new QueryWrapper();
        }
        wrapper.eq("recommended", true);
        wrapper.orderByDesc("update_time");
        wrapper.ne("category_id", categoryImageId);
        wrapper.ne("category_id", categoryVideoId);
        return wrapper;
    }

    /**
     * 新增文章VO对象搜索关键字关联内容
     * @param article
     * @param value
     * @return
     */
    @Override
    public ArticleVO toSelectArticleVO(Article article, String value) {
        ArticleVO vo = this.toArticleVO(article);
        int valueIndex = vo.getArticle().getContent().indexOf(value);
        int startIndex = 0;
        int endIndex = vo.getArticle().getContent().length() - 1;
        int end = valueIndex + 150;
        if (end > endIndex) {
            vo.setSelectContent(vo.getArticle().getContent().substring(valueIndex));
        } else {
            vo.setSelectContent(vo.getArticle().getContent().substring(valueIndex, end));
        }
        return vo;
    }


}
